#define _CRT_SECURE_NO_WARNINGS 1
#include "Stack.h"

//栈的初始化
void StackInit(Stack* ps)
{
	assert(ps);

	//初始化时不设置空间大小
	ps->a = NULL;
	ps->capacity = 0;

	//top指向的是栈顶的下一个元素
	ps->top = 0;
}

//栈的销毁
void StackDestory(Stack* ps)
{
	assert(ps);

	free(ps->a);
	ps->a = NULL;

	ps->top = 0;
	ps->capacity = 0;
}

//压栈
void StackPush(Stack* ps, StackDataType x)
{
	assert(ps);

	//判断是否需要扩容
	if (ps->top == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		StackDataType* newps = (StackDataType*)realloc(ps->a, newcapacity*sizeof(StackDataType));
		if (newps == NULL)
		{
			perror("Stack()::realloc()");
			return;
		}

		ps->a = newps;
		ps->capacity = newcapacity;
	}

	//压栈
	ps->a[(ps->top)++] = x;
}

//出栈
void StackPop(Stack* ps)
{
	assert(ps);
	assert(ps->top > 0);

	ps->top--;
}

//获取栈顶元素
StackDataType GetStackTop(Stack* ps)
{
	assert(ps);
	assert(ps->top > 0);

	return ps->a[ps->top - 1];
}

//判空
bool StackEmpty(Stack* ps)
{
	assert(ps);

	return ps->top == 0;
}

//获取栈中有效元素的个数
int GetStackSize(Stack* ps)
{
	assert(ps);

	return ps->top;
}